<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>订单确认</title>
    <script src="./js/jquery.min.js"></script>
    <link rel="stylesheet" href="https://cdn.bootcss.com/weui/1.1.2/style/weui.min.css">
    <link rel="stylesheet" href="https://cdn.bootcss.com/jquery-weui/1.2.0/css/jquery-weui.min.css">
</head>
<style>
   .right{
       text-align: right
   }
   #money{
       font-size: 25px;
       font-weight:600
   }
   .weui-cells{
       margin-top:0
   }
</style>
<body>
    <div id="payPage">
        <div class="weui-cells weui-cells_form">
            <div class="weui-cell">
                    <div class="weui-cell__hd"><label class="weui-label">用户邮箱</label></div>
                    <div class="weui-cell__bd">
                        <p class="right" id="emil_txt">1075888691@qq.com</p>
                    </div>
            </div>
            <div class="weui-cells__title" id="vip_txt">邀请成功4位，享受4折优惠</div>
            <div class="weui-cell">
              <div class="weui-cell__hd"><label class="weui-label">支付金额(元)</label></div>
                <div class="weui-cell__bd">
                    <input class="weui-input right" disabled id="money" type="number" value="">
                </div>
            </div>
            <div class="weui-cell">
                    <div class="weui-cell__hd"><label class="weui-label">收款方</label></div>
                    <div class="weui-cell__bd">
                        <p class="right">沈阳众志成软件有限公司</p>
                    </div>
            </div>
            <div class="weui-cell">
                <div class="weui-cell__hd"><label class="weui-label">生效时间</label></div>
                <div class="weui-cell__bd">
                    <p class="right">即刻生效</p>
                </div>
            </div>
            <div class="weui-cell">
                    <div class="weui-cell__hd"><label class="weui-label">商品</label></div>
                    <div class="weui-cell__bd">
                        <p class="right">购买网站会员</p>
                    </div>
            </div>
            <div class="weui-cells__title">选择购买时限 (<font id="endDate"></font> 号到期)</div>
            <div class="weui-cell weui-cell_select">
                <div class="weui-cell__bd">
                  <select class="weui-select" id="specoption" onchange="changeSpec()" name="select1">
                    <option selected="" value="1">一个月</option>
                    <option value="3">一个季度</option>
                    <option value="12">一年</option>
                  </select>
                </div>
              </div>
            <div class="weui-cell">
                <div class="weui-cell__bd">
                     <a href="javascript:;" class="weui-btn weui-btn_primary" onclick="wxOrder()">提交订单</a>
                </div>         
            </div>
        </div>
        <div class="weui-msg__extra-area">
                <div class="weui-footer">
                  <p class="weui-footer__links">
                    <a href="javascript:void(0);" class="weui-footer__link">沈阳众志成软件有限公司</a>
                  </p>
                  <p class="weui-footer__text"> ©2018 Ubitcar.com. All Rights Reserved </p>
                </div>
        </div>
    </div>
    <script src="https://cdn.bootcss.com/jquery/1.11.0/jquery.min.js"></script>
    <script src="https://cdn.bootcss.com/jquery-weui/1.2.0/js/jquery-weui.min.js"></script>
    <script>
    $(document).ready(v=>{
        //$('#emil_txt').text(sessionStorage.getItem('userEmail'))
        getCode()
        judgeClient()
        //changeSpec()
        getSessionEmail()
        
    })
    let wxPayData = {
        appidsGloble:'',
        access_tokenGloble:'',
        expires_inGloble:'',
        refresh_tokenGloble:'',
        openidGloble:'',
        scopeGloble:'',
        codeGloble:'',
        prepay_idGloble:'',
        wxSignGloble:'',
        nonceStrGloble:createNonceStr()
    }
    let wxdata = {
        appId:'',
        timeStamp:'',
        nonceStr:'',
        package:'',
        signType:'',
        paySign:''   
    }
    let userinfo = {
        emiled:'',
        moneyed:'',
        sloted:''
    }
    function get_cookie(Name) {
            var search = Name + "=" //查询检索的值
            var returnvalue = ""; //返回值
            if (document.cookie.length > 0) {
                sd = document.cookie.indexOf(search);
                if (sd != -1) {
                    sd += search.length;
                    end = document.cookie.indexOf(";", sd);
                    if (end == -1)
                        end = document.cookie.length;
                    //unescape() 函数可对通过 escape() 编码的字符串进行解码。
                    returnvalue = unescape(document.cookie.substring(sd, end))
                }
            }
            const reg = new RegExp('"',"g");  
            returnvalue = returnvalue.replace(reg, ""); 
            return returnvalue;
        }
    let getSessionEmail = ()=>{
        let userEmailSession = get_cookie('userEmail')
        if(userEmailSession == '' || userEmailSession == null || userEmailSession == 'underfind'){
            $.toptip('请登录后进入此页面！', 2000, 'warning')
            setTimeout(() => {
                window.location.href='http://www.ubitcar.com/login'
            }, 2000);
            return;
        }else{
            $('#emil_txt').text(userEmailSession)
            changeSpec()
        }
    }
    const urls = 'http://www.ubitcar.com:3000'
    let changeSpec = ()=>{
        let v = $('#specoption').val()
        var d = new Date()
        var year = d.getFullYear()
        var month = d.getMonth()+1
        var day = d.getDate()
        //alert(year+'-'+month+'-'+day)
        if(v == 1){
            month = month+1
            $('#endDate').text(year+'-'+month+'-'+day)
            getUserNum($('#emil_txt').text(),v)
        }else if(v == 3){
            month = month+3
            $('#endDate').text(year+'-'+month+'-'+day)
            getUserNum($('#emil_txt').text(),v)
        }else if(v == 12){
            year = year+1
            $('#endDate').text(year+'-'+month+'-'+day)
            getUserNum($('#emil_txt').text(),v)
        }
    }
    //获取应该支付金额方法
    let getUserNum = (emil,slots)=>{
        $.showLoading("加载中...")
        userinfo.emiled = emil
        $.ajax({
            url: urls+'/getUserNum',
            dataType: 'json',
            type: 'post',
            ContentType: "application/json",
            data: {
                emil_s:emil,
                slot:slots
            },
            success: function (res) {
                if(res.code == 200){
                    $('#money').val(res.data.feee.toFixed(2))
                    if(res.data.invitation>=5){
                        $('#vip_txt').text('您成功邀请'+res.data.invitation+'人，享受5折优惠')
                    }else{
                        $('#vip_txt').text('您成功邀请'+res.data.invitation+'人，未能享受优惠')
                    }
                }else{
                    $.toptip(res.msg+'，请联系管理员', 2000, 'warning')
                    setTimeout(function(){
                         window.location = 'http://www.ubitcar.com'
                    },2000)
                }
                $.hideLoading()
            },
            error:function(err){
                $.toptip('网络繁忙，错误码046', 2000, 'warning')
                $.hideLoading()
            }
        })
    }
 
    let judgeClient =()=>{
        if(/Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent)) {
        } else {
            window.location.href = "http://www.ubitcar.com/";
        }
    }
    //元->分
    let yuanToFen = (item)=>{
        var reg = /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/;
        if(reg.test(item)){
            money = parseFloat(item).toFixed(2)*100
            money = money.toFixed(0)
            return money
        }else{
            $.toptip('金额格式有误', 2000, 'warning')
            return false;
        }
    }
    let getUrlParms = (name)=>{
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if (r != null)
            return unescape(r[2]);
            return null;
    }
    function createTimeStamp() {
        var timestamp1 = Date.parse( new Date());
        return timestamp1;
    } 
    function createNonceStr() {  
        return Math.random().toString(36).substr(2, 15);  
    };  

    let getToken = (wxcodes)=>{
        if(wxcodes == null){
        $.toptip('网络繁忙，错误码034', 2000, 'warning')
            return;
        }
        $.ajax({
            url: urls+'/astokenOpid',
            dataType: 'json',
            type: 'post',
            ContentType: "application/json",
            data: {
                code:wxcodes
            },
            success: function (res) {
                $.hideLoading()
                var obj = eval(res)
                var dataObj = JSON.parse(obj.data)
                if(dataObj.errcode == 40163){
                $.toptip('请从新进入此页面', 2000, 'warning')
                    window.location = 'http://www.ubitcar.com'
                    return;
                }
                wxPayData.access_tokenGloble = dataObj.access_token
                wxPayData.expires_inGloble = dataObj.expires_in
                wxPayData.refresh_tokenGloble = dataObj.refresh_token
                wxPayData.openidGloble = dataObj.openid
                wxPayData.scopeGloble = dataObj.scope
            },
            error:function(err){
            $.toptip('网络繁忙，错误码035', 2000, 'warning')
            $.hideLoading()
            }
        });
    }
    function getCode(){
        $.showLoading("加载中...")
        wxPayData.codeGloble = getUrlParms("code")
        getToken(wxPayData.codeGloble)
    }
    let wxOrder = ()=>{
        let _this = this;
        // if($('#emil_txt').text()=='' || $('#emil_txt').text()=='underfind'){
        //     $.toptip('用户邮箱获取失败', 2000, 'warning')
        //     window.location = 'http://www.ubitcar.com'
        //     return false
        // }
        var re = /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$/;
        if (re.test($('#emil_txt').text())) {
                
        } else {
            $.toptip('邮箱格式不正确', 2000, 'warning')
            return false
        }
        let jine = $('#money').val()
        let money =  yuanToFen(jine)
        if(!money){
            return false;
        }
        userinfo.moneyed = money
        userinfo.sloted = $('#specoption').val()
        $.showLoading("加载中...")
        $.ajax({  
            url: urls+'/wxPayOrder',  
            dataType: 'json',  
            type: 'post',  
            ContentType: "application/json",  
            data: {
                attach:'沈阳众志成',  
                body: '购买会员',// 支付详情  
                mch_id:'1321518401',
                openid:wxPayData.openidGloble,
                total_fee:money,
                notify_url:urls+'/wxNoctice'
            },  
            success:function(data) {
                if(data.code == 200){
                    wxPayData.prepay_idGloble = data.prepay_id
                    wxPaysignFunc()
                }else{
                    $.hideLoading()
                    $.toptip('网络繁忙，错误码038', 2000, 'warning')
                }  
            },  
            error:function(err){
                $.hideLoading()
                $.toptip('网络繁忙，错误码037', 2000, 'warning')
            }
        });  
    }
    let wxPaysignFunc = ()=>{
        $.ajax({  
            url: urls+'/wxpaysign_api',  
            dataType: 'json',  
            type: 'post',  
            ContentType: "application/json",  
            data: null,  
            success:function(data) {
                if(data.code == 200){
                    wxPayData.wxSignGloble = data.data
                    //$.toast('微信签名接口返回成功')
                    $.hideLoading()
                    onBridgeReady()
                }  
            },  
            error:function(err){
                $.hideLoading()
                $.toptip('网络繁忙，错误码039', 2000, 'warning')
            }
        });  
    }
    function onBridgeReady(){
            WeixinJSBridge.invoke(
                'getBrandWCPayRequest', {
                    "appId":wxPayData.wxSignGloble.appId,     //公众号名称，由商户传入     
                    "timeStamp":""+wxPayData.wxSignGloble.timeStamp+"",         //时间戳，自1970年以来的秒数     
                    "nonceStr":wxPayData.wxSignGloble.nonceStr, //随机串     
                    "package":wxPayData.wxSignGloble.package,     
                    "signType":wxPayData.wxSignGloble.signType, //微信签名方式：     
                    "paySign":wxPayData.wxSignGloble.signed //微信签名 
                },
                function(res){
                    if(res.err_msg == "get_brand_wcpay_request:ok" ) {
                        $.ajax({
                            url:urls+'/getPayParameter',
                            type:'post',
                            ContentType: "application/json",  
                            dataType: 'json',  
                            data:{
                                openid:wxPayData.openidGloble,
                                emil:userinfo.emiled,
                                money:userinfo.moneyed,
                                slot:userinfo.sloted
                             },
                            success:function(data){
                                
                            }
                        })
                        window.location = 'http://www.ubitcar.com/app/success.html'
                    }else{
                        $.ajax({
                            url:urls+'/void/v1/failmsg',
                            type:'post',
                            ContentType: "application/json",  
                            dataType: 'json',  
                            data:{
                                notice:res.err_msg
                             },
                            success:function(data){
                                
                            }
                        })
                        window.location = 'http://www.ubitcar.com/app/error.html'                           
                    }     // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回    ok，但并不保证它绝对可靠。 
                }
            ) 
        }
    </script>
</body>

</html>